package dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import tables.BindingTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

import entity.Binding;

public class BindingDao extends AbstractDao<BindingTable, Binding> {

	public BindingDao(final String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final Binding newBinding) {
		newBinding.setId(getNextId());
		final BindingTable table = deserializeFromXml();
		table.getRows().add(newBinding);
		serializeToXml(table);
	}

	@Override
	public void update(final Binding entity) {
		final BindingTable table = deserializeFromXml();
		for (final Binding row : table.getRows()) {
			if (row.getRoute().equals(entity.getId())) {
				row.setBind(entity.getBind());
				break;
			}
		}
		serializeToXml(table);
	}

	@Override
	public Binding get(final Serializable id) {
		final BindingTable table = deserializeFromXml();
		for (final Binding row : table.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Binding> getAll() {
		final BindingTable flightTable = deserializeFromXml();
		return flightTable.getRows();
	}

	@Override
	public void delete(final Serializable id) {
		final BindingTable table = deserializeFromXml();
		Binding toBeDeleted = null;
		for (final Binding row : table.getRows()) {
			if (row.getBind().equals(id)) {
				toBeDeleted = row;
				break;
			}
		}
		table.getRows().remove(toBeDeleted);
		serializeToXml(table);
	}

	public List<String> getAllRoute() {
		final BindingTable catalogTable = deserializeFromXml();
		List<String> listID= new ArrayList();
		for (Binding c : catalogTable.getRows()) {
			listID.add(c.getRoute());
		}
		return listID;
	}
	public List<String> getAllTransportbyID() {
		final BindingTable catalogTable = deserializeFromXml();
		List<String> listID= new ArrayList();
		for (Binding c : catalogTable.getRows()) {
			listID.add(c.getRoute());
		}
		return listID;
	}
	@Override
	protected Class<BindingTable> getTableClass() {
		return BindingTable.class;
	}
}
